#include "filter.h"

/* Reference: 
 * [常见的数字滤波算法](https://zhuanlan.zhihu.com/p/58117237)
 *
 */

/* 限幅滤波算法 */
#define FILTER_LIMIT 30
void clipping_filter(ulong * value)
{
    static ulong last_value = 0xffffffff;
    ulong diff_value;

    if(last_value == 0xffffffff)
        last_value = *value;

    diff_value = last_value > *value ? last_value - *value : *value - last_value;
    // if(abs(last_value - value) < FILTER_LIMIT)
    if(diff_value <= FILTER_LIMIT)
        last_value = *value;

    *value = last_value;
}


/* 滑动平均滤波算法 */
#define FILTER_LEVEL 30

void moving_avaraging_filter(ulong * value)
{
    static uchar index = 0;
    static bit first_loop = 1;
    static ulong pdata buff[FILTER_LEVEL] = {0};
    
    uchar end;
    uchar i;
    
    buff[index ++] = *value;

    if(index == FILTER_LEVEL)
    {
        i = 0;
        first_loop = 0;
    }
    
    end = first_loop ? index : FILTER_LEVEL;

    *value = 0;
    for(i =0; i < end; i++)
        *value += buff[i];

    *value = *value / end;
}

#define FILTER_SAMPLE 10
/* 中值滤波 */
void median_filter(ulong * value)
{
    static ulong pdata buff[FILTER_SAMPLE] = {0};
    
     
}
/* 算术平均滤波 */
#define FILTER_SAMPLE_1 10
ulong digital_averaging_filter(Func sample_func)
{
    uchar i;
    ulong value = 0;

    for(i = 0; i < FILTER_SAMPLE_1; i++)
    {
        value += sample_func();
    }
    return value / FILTER_SAMPLE_1;
}

/* 限幅滤波算法 */
